package getCourseM3U8;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Scanner;

public class getM3U8 {
	
	private static final String courseUrl = "http://librarywap.koolearn.com/getProductInfo?productId="; 
	private static final String treeBaseUrl = "http://librarywap.koolearn.com/tree?productId=";
	private static final String m3u8BaseUrl = "http://librarywap.koolearn.com/getVideoUrl?courseUnitId=";
	private static String root_dir = null;
	/**
	 * 发送get请求并取回响应
	 * @param src_url
	 * @return
	 * @throws IOException
	 */
	public static String getReq(String src_url) throws IOException{
        String path = src_url; 
        //1, 取得URL对象
        URL url = new URL(path);
        //2, 建立连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //3, 请求方式为GET
		conn.setRequestMethod("GET");
        //4, 允许输入 
        conn.setDoInput(true); 
        //5, 获取连接的输入流（输入主机返回的数据），并放在字符串中 
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        String str = null;
        StringBuilder sb = new StringBuilder();
        while((str = br.readLine())!=null) {
        	sb.append(str).append('\n');
        }
        return sb.toString();
	}
	/**
	 * 取得课程名称
	 * @param courseID
	 * @return
	 * @throws IOException
	 */
	public static String getName(Integer courseID) throws IOException {
		String res = getReq(courseUrl + courseID);
		JSONObject jObject = JSONObject.parseObject(res);
		return jObject.getJSONObject("data").getString("name");
	}
	/**
	 * 取得课程目录
	 * @param courseID
	 * @return
	 * @throws IOException
	 */
	public static String getTree(Integer courseID) throws IOException {
		String res = getReq(treeBaseUrl + courseID);
		return res;
	}
	/**
	 * 转换成具体的 课程名称 和m3u8地址的对应关系，用json存储
	 * @param jsonTree
	 * @throws IOException
	 */
	public static JSONArray getM3U8List(Integer courseID) throws IOException{
		Integer order = 0;
		//解析上一步得到的目录的课程的下载地址
		JSONArray jsonArray = JSONArray.parseArray(getTree(courseID));
		System.out.println("正在获取播放地址...");
		//用于存储结果
		JSONArray res = new JSONArray();
		
		for(int i=0;i<jsonArray.size();i++) {
			JSONObject jo = jsonArray.getJSONObject(i);
			if(jo.getInteger("type")!=2) continue;
			Integer currentId = jo.getInteger("id");
			//取得播放地址
			String m3u8Address = JSONObject.parseObject(getReq(m3u8BaseUrl+ currentId)).getString("data");
			//System.err.println(m3u8Address);
			//重新形成json数组
			JSONObject currentResult = new JSONObject();
				currentResult.put("id", currentId);
				currentResult.put("m3u8", m3u8Address);
				currentResult.put("name", String.format("%03d",order++) + " " + jo.getString("name").replaceAll("\n", ""));
			res.add(currentResult);
			if(order%10==0) System.out.printf("已完成 %d/%d\n",order,jsonArray.size());
		}
		System.out.println("播放地址获取完毕");
		return res;
	}
	
	public static void download(JSONArray m3u8List) throws IOException {
		//重新取得解析的信息
		System.out.println("正在下载m3u8文件...");
		for(int i=0;i<m3u8List.size();i++) {
			JSONObject jsonObject = m3u8List.getJSONObject(i);
			String videoName = jsonObject.getString("name"); 
			String m3u8Content = getReq(jsonObject.getString("m3u8"));
			//将密钥分发地址替换为永久的
			m3u8Content = m3u8Content.replaceAll("URI=\".*\"", "URI=\"http://kbtxwer.gitee.io/koolean_key.bin\"");
			FileOutputStream fos = null;
			try{
				fos = new FileOutputStream(new File(root_dir + videoName + ".m3u8"));
			}catch(IOException e){
				 System.err.println("出现错误，当前文件名用纯序号替代");
				 e.printStackTrace();
				 fos = new FileOutputStream(root_dir + String.format("%03d", i) + ".m3u8");
			 }
			fos.write(m3u8Content.getBytes());
			fos.close();
			if(i%10==0) System.out.printf("已完成 %d/%d\n",i,m3u8List.size());
		}
		
		System.out.println("下载完毕");
	}
	
	public static void main(String[] args) throws Exception{
		// TODO 自动生成的方法存根
		Scanner input=new Scanner(System.in);
		System.err.println("请输入课程id：");
		while (input.hasNextInt()) {
			
			Integer cid = input.nextInt();
			if(cid<1) break;
			//input.close();
			String cName = getName(cid); 
			System.err.println(cName);
			
			if(cName==null) {System.err.println("当前id下不存在课程！");break;}
			root_dir = cName + '\\';
			
			File RT_dir = new File(root_dir);
			if(!RT_dir.exists()) {
				RT_dir.mkdirs();
			}
			
			
			JSONArray mList = getM3U8List(cid);
			
			//System.out.println(mList);
			download(mList);
			System.err.println("请输入课程id：");
		}
		
		input.close();
	}

}
